package com.example.earthed.controller;

import com.example.earthed.entity.Super;
import com.example.earthed.model.Result;
import com.example.earthed.service.SuperService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
@RequestMapping(path = "/app/super")
public class SuperController {

    @Autowired
    private SuperService superService;

    /**
     * 管理员登录
     * @param request
     * @param superAdmin
     * @return
     */
    @PostMapping("/login")
    public Result<Super> login(HttpServletRequest request, @RequestBody Super superAdmin) {
        String password = superAdmin.getPwd();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        LambdaQueryWrapper<Super> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Super::getUserName, superAdmin.getUserName());
        Super theSuper = superService.getOne(queryWrapper);

        if (theSuper == null) {
            return Result.error("账号或密码错误");
        }

        if (!theSuper.getPwd().equals(password)) {
            return Result.error("账号或密码错误");
        }

        if (theSuper.getStatus() == 0) {
            return Result.error("该账号已被禁用");
        }

        request.getSession().setAttribute("super", theSuper.getId());
        return Result.success(theSuper);
    }

    /**
     * 管理员退出登录
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public Result<String> logout(HttpServletRequest request) {
        request.getSession().removeAttribute("super");
        return Result.success("退出成功");
    }

    /**
     * 获取管理员个人信息
     * @param request
     * @return
     */
    @GetMapping("/person/information")
    public Result<Super> information(HttpServletRequest request) {
        Long superId = (Long) request.getSession().getAttribute("super");
        return Result.success(superService.getById(superId));
    }

    /**
     * 修改管理员个人信息
     * @param request
     * @param superAdmin
     * @return
     */
    @PutMapping("/person/information")
    public Result<String> updateInformation(HttpServletRequest request, @RequestBody Super superAdmin) {
        Long superId = (Long) request.getSession().getAttribute("super");
        superAdmin.setId(superId);
        superService.updateById(superAdmin);
        return Result.success("修改个人信息成功");
    }

    /**
     * 新增管理员
     * @param superAdmin
     * @return
     */
    @PostMapping("/add")
    public Result<String> addSuper(@RequestBody Super superAdmin) {
        // md5加密密码
        superAdmin.setPwd(DigestUtils.md5DigestAsHex(superAdmin.getPwd().getBytes()));
        superService.save(superAdmin);
        return Result.success("新增管理员成功");
    }

}